package com.example.shiro.service.impl;

import com.example.shiro.domain.Permission;
import com.example.shiro.domain.Role;
import com.example.shiro.domain.User;
import com.example.shiro.dto.AddRoleDto;
import com.example.shiro.dto.AddUserDto;
import com.example.shiro.repository.RoleRepository;
import com.example.shiro.repository.UserRepository;
import com.example.shiro.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @ Author     ：jujh
 * @ Date       ：Created in 17:14 2018/10/29
 * @ Description：
 */
@Service
@Transactional
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    //添加用户
    @Override
    public User addUser(AddUserDto userDto) {
        User user = new User();
        user.setName(userDto.getUsername());
        user.setPassword(userDto.getPassword());
        userRepository.save(user);
        return user;
    }

    //添加角色
    @Override
    public Role addRole(AddRoleDto addRoleDto) {
        User user = userRepository.findOne(addRoleDto.getUserId());
        Role role = new Role();
        role.setRoleName(addRoleDto.getRoleName());
        role.setUser(user);
        Permission permission1 = new Permission();
        permission1.setPermission("create");
        permission1.setRole(role);
        Permission permission2 = new Permission();
        permission2.setPermission("update");
        permission2.setRole(role);
        List<Permission> permissions = new ArrayList<Permission>();
        permissions.add(permission1);
        permissions.add(permission2);
        role.setPermissions(permissions);
        roleRepository.save(role);
        return role;
    }

    //查询用户通过用户名
    @Override
    public User findByName(String name) {
        return userRepository.findByName(name);
    }

    @Override
    public User findByNameAndPassword(String name, String password) {
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        Example<User> example = Example.of(user);
        return userRepository.findOne(example);
    }

}
